package com.hnkywl.sts.service.sfgl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hnkywl.sts.dao.base.SjzdzDao;
import com.hnkywl.sts.dao.htgl.CghtDao;
import com.hnkywl.sts.dao.organ.EjzhDao;
import com.hnkywl.sts.dao.organ.GsjgDao;
import com.hnkywl.sts.dao.sfgl.SkshDao;
import com.hnkywl.sts.dao.zjfp.KyzjDao;
import com.hnkywl.sts.dao.zjfp.KyzjzsDao;
import com.hnkywl.sts.dao.zjgl.PjglDao;
import com.hnkywl.sts.dao.zjgl.XyzDao;
import com.hnkywl.sts.entity.base.Sjzdz;
import com.hnkywl.sts.entity.htgl.Cght;
import com.hnkywl.sts.entity.htgl.Fkfs;
import com.hnkywl.sts.entity.organ.Ejzh;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.entity.sfgl.Sfk;
import com.hnkywl.sts.entity.zjfb.Kyzj;
import com.hnkywl.sts.entity.zjfb.Kyzjzs;
import com.hnkywl.sts.entity.zjgl.Bzj;
import com.hnkywl.sts.entity.zjgl.Pj;
import com.hnkywl.sts.entity.zjgl.Xyz;
import com.hnkywl.sts.service.base.BmService;
import com.hnkywl.sts.service.base.DxpzService;
import com.hnkywl.sts.service.organ.KhhService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.service.zjgl.PjglService;
import com.hnkywl.sts.service.zjgl.XyzService;
import com.hnkywl.sts.util.BaseUtils;
import com.hnkywl.sts.util.CalcUtils;
import com.hnkywl.sts.util.DateUtil;
import com.hnkywl.sts.util.ReflectionUtils;
import net.ruixin.orm.hibernate.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: cyh
 * Date: 13-4-19
 * Time: 上午10:41
 * To change this template use File | Settings | File Templates.
 */
@Service
public class SkshService {
    private BmService bmService;
    private SkshDao skshDao;
    private KhhService khhService;
    private PjglService pjglService;
    private KyzjDao kyzjDao;
    private KyzjzsDao kyzjzsDao;
    private XyzService xyzService;
    private XyzDao xyzDao;
    private GsjgDao gsjgDao;
    private PjglDao pjglDao;
    private EjzhDao ejzhDao;
    private DxpzService dxpzService;
    private SjzdzDao sjzdzDao;
    private CghtDao cghtDao;

    /**
     * 查询付款审核列表
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Transactional
    public String findAllSksh(Long kxsy, Date skshStart, Date skshEnd, String bm, String sbgsMc, Long sbgsId, String gldwMc, String zt, String skr, int pageNo, int pageSize) {
        Long nbgsIds = null;
        if (sbgsId != null && sbgsMc.equals(gsjgDao.get(sbgsId).getJc())) {
            nbgsIds = nbgsIds;
        }
        Page<Sfk> sfkPage = this.skshDao.findSklxList(kxsy, skshStart, skshEnd, bm, sbgsMc, nbgsIds, gldwMc, zt, skr, pageNo, pageSize);
        List<Sfk> ygList = sfkPage.getResult() == null ? new ArrayList<Sfk>() : sfkPage.getResult();
        Double sfzje = 0d;
        if (ygList.size() > 0) {
            for (Sfk s : ygList) {
                sfzje += s.getSfje();
            }
        }
        String ygJson = BaseUtils.fetchCollectionToJson(ygList, "id", "bm", "sfkrq", "sfklx", "gldw.qc", "kxyt.z", "kxsy.z", "fkfs.z", "sfje", "pjlx.z", "kxlx", "sbgs.jc", "sbr.xm", "bz", "zt", "shrq", "khfksj", "pjhm", "ye", "fplx", "sfhz");
        return "{\"total\":" + sfkPage.getTotalCount() + ",\"rows\":[" + ygJson + "]}";
    }

    @Transactional
    public String findskshByXshtList(Long cghtId, int pageNo, int pageSize) {
        Page<Sfk> sfkPage;
        sfkPage = this.skshDao.findskshByCghtList(cghtId, pageNo, pageSize);
        List<Sfk> ygList = sfkPage.getResult() == null ? new ArrayList<Sfk>() : sfkPage.getResult();
        String ygJson = BaseUtils.fetchCollectionToJson(ygList, "id", "bm", "sfkrq", "sfklx", "gldw.qc", "hklx.z", "sfje", "pjlx.z", "kxlx", "sbgs.jc", "sbr.xm", "bz", "zt");
        return "{\"total\":" + sfkPage.getTotalCount() + ",\"rows\":[" + ygJson + "]}";
    }

    public String findBzjSkList(Long gldwId,Integer fplx, String htms, int pageNo, int pageSize) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        Page page = null;
        if (StringUtils.equals("xsms", htms)) {
            page = skshDao.findBzjSkXsmsList(gldwId,fplx, pageNo, pageSize);
        } else {
            page = skshDao.findBzjSkList(gldwId,fplx, pageNo, pageSize);
        }
        return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + gson.toJson(page.getResult()) + "}";
    }


    public String findHthkSkList(Long gldwId, Integer fplx, int pageNo, int pageSize) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        Page page = skshDao.findHthkSkList(gldwId, fplx, pageNo, pageSize);
        return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + gson.toJson(page.getResult()) + "}";
    }

    /**
     * 首页显示收款单数
     *
     * @return
     */
    public Sfk findSfkByBm(String SfkBm) {
        return this.skshDao.findSfkByBm(SfkBm);
    }


    /**
     * 首页显示收款单数
     *
     * @return
     */
    public String findAllSksh() {
        return this.skshDao.findAllSksh();
    }

    /**
     * 保存收款审核信息
     *
     * @param sfk 收款审核实体
     * @return
     */
    @Transactional
    public void saveSksh(Sfk sfk, String sfje) {
        nullId(sfk);
        if (sfk.getBz() != null) {
            Pattern p = Pattern.compile("\t|\r|\n");
            Matcher m = p.matcher(sfk.getBz());
            String bz = m.replaceAll("");
            sfk.setBz(bz);
        }
        sfk.setWlzlx(0);
        sfk.setSfkrq(sfk.getKhfksj());
        sfk.setDateCreated(new Date());
        sfk.setSfje(Double.parseDouble(sfje.replace(",", "").replace("，", "")));
        sfk.setLastUpdated(sfk.getDateCreated());
        sfk.setCreateUser(YgService.getCurrentYg());
        sfk.setCreateOrgan(YgService.getCurrentYg().getZggs());
        sfk.setCreateDepartment(YgService.getCurrentYg().getZgjg());
        sfk.setSfpz(1);
        sfk.setBm(this.bmService.getSfdbm("SK"));
        this.skshDao.save(sfk);
    }

    @Transactional
    public void saveCzSksh(Sfk sfk, String sfje) {
        nullId(sfk);
        if (sfk.getBz() != null) {
            Pattern p = Pattern.compile("\t|\r|\n");
            Matcher m = p.matcher(sfk.getBz());
            String bz = m.replaceAll("");
            sfk.setBz(bz);
        }
        sfk.setWlzlx(0);

        // 款项用途
        if (null != sfk.getKxsy() && null != sfk.getKxsy().getId()) {
            Sjzdz kxsy = sjzdzDao.get(sfk.getKxsy().getId());
            if (kxsy.getZ().equals("合同保证金")) {
                sfk.setSfBzj(1);
            }
        } else {
            sfk.setKxsy(null);
        }

        if (StringUtils.isNotBlank(sfk.getPjhm())) {
            sfk.setPjhm(sfk.getPjhm().trim());
        }

        sfk.setSfhz("0");
        sfk.setSfkrq(sfk.getKhfksj());
        sfk.setDateCreated(new Date());
        sfk.setSfje(Double.parseDouble(sfje.replace(",", "").replace("，", "")));
        sfk.setLastUpdated(sfk.getDateCreated());
        sfk.setCreateUser(YgService.getCurrentYg());
        sfk.setCreateOrgan(YgService.getCurrentYg().getZggs());
        sfk.setCreateDepartment(YgService.getCurrentYg().getZgjg());
        sfk.setSfpz(1);
        sfk.setSfjstx("0");
        sfk.setBm(this.bmService.getSfdbm("SK"));
        //  sfk.setJfejzh(ejzhDao.get(sfk.getJfejzh().getId()));
        sfk.setYe(sfk.getSfje());
        this.skshDao.save(sfk);
    }

    @Transactional
    public void saveTz(Sfk sfkTemp) {
        Sfk clone = this.findSkshDetail(sfkTemp.getId());
        nullId(sfkTemp);
        // 款项用途
        if (null != sfkTemp.getKxsy() && null != sfkTemp.getKxsy().getId()) {
            Sjzdz kxsy = sjzdzDao.get(sfkTemp.getKxsy().getId());
            clone.setKxsy(kxsy);
            if (kxsy.getZ().equals("合同保证金")) {
                clone.setSfBzj(1);
            }
        }
        clone.setZt("ytz");
        clone.setLastUpdated(new Date());
        clone.setFplx(sfkTemp.getFplx());
        clone.setMxts(sfkTemp.getMxts());
        clone.setTxl(sfkTemp.getTxl());
        Gsjg gsjg = this.gsjgDao.get(clone.getGldw().getId());
        // 按比例释放，先扣除贴息
//        if (gsjg.getBzjfs() == 1) {
//            Sjzdz fkfs = this.sjzdzDao.get(clone.getFkfs().getId());
//            if (fkfs.getZ().equals("承兑")) {
//                long calDays;
//                long reduceDays = DateUtil.getDay(clone.getEndDate(), clone.getKhfksj());
//                calDays = reduceDays - clone.getMxts();
//                Double tx = 0.0;
//                if (calDays > 0) {
//                    tx = CalcUtils.round(((clone.getSfje() * clone.getTxl() / 100) / 30.0) * calDays, 2);
//                }
//                clone.setTx(CalcUtils.round(tx, 2));
//                clone.setTxye(CalcUtils.round(tx, 2));
//                clone.setJstx(calDays);
//                clone.setYe(CalcUtils.round(clone.getSfje() - tx, 2));
//                clone.setSfjstx("1");
//            } else {
//                clone.setYe(clone.getSfje());
//            }
//        } else {
//            clone.setYe(clone.getSfje());
//        }
        this.skshDao.save(clone);
    }


    @Transactional
    public void saveHzSksh(Sfk sfk, Long hzsfkyt, Double hzje, Integer fplx, String str) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        StringBuilder sb = new StringBuilder();
        // 保存款项用途
        Sfk clone = this.findSkshDetail(sfk.getId());
        nullId(sfk);
        // 款项用途
        if (null != sfk.getKxsy() && null != sfk.getKxsy().getId()) {
            Sjzdz kxsy = sjzdzDao.get(sfk.getKxsy().getId());
            if (kxsy.getZ().equals("合同保证金")) {
                clone.setSfBzj(1);
            }
        }
        clone.setYe(sfk.getYe() - hzje);
        clone.setSfhz("1");
        clone.setLastUpdated(new Date());
        // 保存划转结果
        Sfk hzskf = new Sfk();
        if (sfk.getYe() == hzje) {
            if (clone.getSfjstx().equals("1") && clone.getTx() > 0) {
                hzskf.setTx(clone.getTx());
                hzskf.setTxl(clone.getTxl());
                hzskf.setJstx(clone.getJstx());
                hzskf.setMxts(clone.getMxts());
            }
        }
        hzskf.setSfjstx(clone.getSfjstx());
        hzskf.setWlzlx(0);
        hzskf.setSfhz("0");
        hzskf.setYe(hzje);
        hzskf.setSfje(hzje);
        hzskf.setPjhm(clone.getPjhm());
        hzskf.setKxyt(clone.getKxyt());
        if (str.equals("0")) {
            hzskf.setZt("ytz");
            hzskf.setSfpz(1);
            hzskf.setShrq(clone.getShrq());
        } else if (str.equals("1")) {
            hzskf.setZt("ytj");
            hzskf.setSfpz(0);
        } else if (str.equals("2")) {
            hzskf.setZt("ytj");
            hzskf.setSfpz(1);
        } else {
            hzskf.setZt("ytz");
            hzskf.setSfpz(0);
            hzskf.setShrq(clone.getShrq());
        }
        hzskf.setHzsj(new Date());
        hzskf.setHzr(YgService.getCurrentYg());
        // 款项用途
        Sjzdz kxsy = sjzdzDao.get(hzsfkyt);
        hzskf.setKxsy(kxsy);
        if (null != kxsy && null != kxsy.getId()) {
            if (kxsy.getZ().equals("合同保证金")) {
                sfk.setSfBzj(1);
            }
            sb.append((clone.getBz() == null ? "" : clone.getBz()) + "(" + sf.format(new Date()) + "日，其中" + hzje + "元作为" + kxsy.getZ() + "使用)");
            clone.setBz(sb.toString().trim());
        }
        hzskf.setPjlx(clone.getPjlx());
        hzskf.setSfkrq(clone.getSfkrq());
        hzskf.setGldw(clone.getGldw());
        hzskf.setGlkhh(clone.getGlkhh());
        hzskf.setKxlx(clone.getKxlx());
        hzskf.setSbgs(clone.getSbgs());
        hzskf.setSbbm(clone.getSbbm());
        hzskf.setSbr(clone.getSbr());
        hzskf.setSfklx(3);
        hzskf.setNbhzsfk(clone);
        hzskf.setZdhz(0);
        hzskf.setFplx(fplx);
        hzskf.setFkfs(clone.getFkfs());
        hzskf.setStartDate(clone.getStartDate());
        hzskf.setEndDate(clone.getEndDate());
        hzskf.setKhfksj(clone.getKhfksj());
        hzskf.setDateCreated(new Date());
        hzskf.setLastUpdated(hzskf.getDateCreated());
        hzskf.setCreateUser(YgService.getCurrentYg());
        hzskf.setCreateOrgan(YgService.getCurrentYg().getZggs());
        hzskf.setCreateDepartment(YgService.getCurrentYg().getZgjg());
        hzskf.setBm(this.bmService.getSfdbm("SK"));
        hzskf.setJfejzh(clone.getJfejzh());
        this.skshDao.save(hzskf);
        this.skshDao.save(clone);
    }


    /**
     * 更新收款审核信息
     *
     * @param sfk 收款审核实体
     * @return
     */
    @Transactional
    public void updateSksh(Sfk sfk, String sfje) {
        Sfk clone = this.findSkshDetail(sfk.getId());
        nullId(sfk);
        clone = (Sfk) ReflectionUtils.getInstance(clone, sfk);
        clone.setSfje(Double.parseDouble(sfje.replace(",", "").replace("，", "")));
        clone.setLastUpdated(new Date());
        clone.setWlzlx(0);
        clone.setSfkrq(clone.getKhfksj());
        this.skshDao.save(clone);
    }

    /**
     * 删除收款审核信息
     *
     * @param id 收款审核id
     * @return
     */
    @Transactional
    public void deleteSksh(Long id) {
        Sfk sfk = skshDao.get(id);
        sfk.setLastUpdated(new Date());
        sfk.setDeleted(1);
        if (sfk.getZt().equals("yrz") || sfk.getZt().equals("yth")) {
            List<Pj> rzpjList = pjglDao.getPjBySkId(sfk.getId());
            if (rzpjList.size() > 0) {
                for (Pj pj : rzpjList) {
                    if (pj.getStatus() == 2 || pj.getStatus() == 3) {
                        throw new RuntimeException("票据已托收或承兑，请先退回!");
                    }
                    pj.setDeleted(1);
                    pj.setLastUpdated(new Date());
                    pjglService.savePjgl(pj);
                }
                sfk.setPjList(null);
            }
            List<Xyz> rzxyzList = xyzDao.getXyzBySFKId(sfk.getId());
            if (rzxyzList.size() > 0) {
                for (Xyz xyz : rzxyzList) {//应收信用证可以变现
                    if (xyz.getStatus() == 3) {
                        throw new RuntimeException("信用证已变现，请先取消还款");
                    }
                    xyz.setLastUpdated(new Date());
                    xyz.setDeleted(1);
                    xyzService.saveOldXyz(xyz);
                }
                sfk.setXyzList(null);
            }
        }
        this.skshDao.save(sfk);
    }

    /**
     * 查询收款审核明细
     *
     * @param id
     * @return
     */
    @Transactional
    public Sfk findSkshDetail(Long id) {
        return this.skshDao.get(id);
    }

    /**
     * 修改收款审核时间
     *
     * @param
     * @return
     */
    @Transactional
    public void xgshrq(Sfk sksh) {
        Sfk sfk = this.findSkshDetail(sksh.getId());
        sfk.setShrq(sksh.getShrq());
        this.skshDao.save(sfk);
    }

    /**
     * ajax远程验证
     *
     * @param value 验证值
     * @param field 验证字段
     * @return
     */
    public boolean ajaxValidate(Long id, String value, Object field) {
        return skshDao.checkUnique(id, value, field);
    }

    @Transactional
    public void SkshTj(Long id, String status) {
        Sfk sfk = this.findSkshDetail(id);
        sfk.setZt(status);
        sfk.setShrq(new Date());
        sfk.setLastUpdated(new Date());
        this.skshDao.save(sfk);
    }

    @Transactional
    public void SkshQxsh(Long id, String status) {
        Sfk sfk = this.findSkshDetail(id);
        sfk.setZt(status);
        sfk.setLastUpdated(new Date());
        if (sfk.getKxyt().getZ().equals("充值")) {
            Ejzh ejzh = sfk.getJfejzh();
            ejzh.setKyye((ejzh.getKyye() == null ? 0 : ejzh.getKyye()) - sfk.getSfje());
            ejzh.setYe((ejzh.getYe() == null ? 0 : ejzh.getYe()) - sfk.getSfje());
            ejzhDao.save(ejzh);
        }
        this.skshDao.save(sfk);
    }

    @Transactional
    public void SkshTh(Long id, String status) {
        Sfk sfk = this.findSkshDetail(id);
        sfk.setZt(status);
        sfk.setLastUpdated(new Date());
        this.skshDao.save(sfk);
    }

    /**
     * 审核状态
     *
     * @param id
     * @param status
     */
    @Transactional
    public void changeStatus(Long id, String status) {
        Sfk sfk = this.findSkshDetail(id);
        sfk.setZt(status);
        sfk.setLastUpdated(new Date());
        if (status.equalsIgnoreCase("ysh")) {
            sfk.setShr(YgService.getCurrentYg());
            sfk.setShrq(new Date());
        }
//        Ejzh ejzh = sfk.getJfejzh();
//        if (sfk.getKxyt().getZ().equals("充值")) {
//            ejzh.setKyye((ejzh.getKyye() == null ? 0 : ejzh.getKyye()) + sfk.getSfje());
//            ejzh.setYe((ejzh.getYe() == null ? 0 : ejzh.getYe()) + sfk.getSfje());
//            ejzhDao.save(ejzh);
//        }
        sfk.setYe(sfk.getYe());
        this.skshDao.save(sfk);
//        if (sfk.getKxyt().getZ().equals("充值") && status.equalsIgnoreCase("ysh")) {
//            dxpzService.sendSMS("XJJYTX", ejzh.getKh().getLxsj(), ejzh.getKh().getJc(), new SimpleDateFormat("yyyy年MM月dd日").format(new Date()),
//                    "充值", String.format("%.2f", sfk.getSfje()), String.format("%.2f", ejzh.getYe()));
//        }
    }


    /**
     * 收款审核操作流程
     *
     * @param skshId
     * @return
     */
    @Transactional
    public void checkSkshPj(Long skshId, List<Pj> pjList) {
        Sfk sfk = this.findSkshDetail(skshId);
        List<Pj> rzpjList = pjglDao.getPjBySkId(sfk.getId());
        if (rzpjList.size() > 0) {
            for (Pj p : rzpjList) {
                p.setDeleted(1);
                pjglDao.save(p);
            }
        }
        Double pjrzze = 0.0;//票据入账总额
        for (Pj p : pjList) {
            pjrzze += Double.parseDouble(p.getDqje().toString());
        }
        Double Sfkje = Double.parseDouble(sfk.getSfje().toString());
        if (Sfkje != (pjrzze * 100) / 100) {
            throw new RuntimeException("票据总金额必须等于收付款金额");
        }
        for (Pj pj : pjList) {
            if (!pjglService.checkYspjhm(YgService.getCurrentYgGsId(), pj.getPjhm())) {//如果票据号码重复
                throw new RuntimeException("票据号码为" + pj.getPjhm() + "的票据号码重复");
            }
            pj.setPjlx((sfk.getPjlx().getZ()).equals("银票") ? 0 : 1);
            pj.setNbgs(sfk.getSbgs());
            pj.setDqje(Double.parseDouble(pj.getDqje().toString()));
            if (sfk.getSfklx() == 1 || sfk.getSfklx() == 2) {
                pj.setSfk(sfk);
            } else {
                pj.setSk(sfk);
            }
            pj.setJpdw(sfk.getGldw());
            sfk.setShrq(new Date());
            pj.setLastUpdated(new Date());
            pjglService.savePjgl(pj, 0);
        }
        sfk.setLastUpdated(new Date());
        sfk.setZt("yrz");
        sfk.setShr(YgService.getCurrentYg());
        this.skshDao.save(sfk);
    }


    public static String convertScienceNum(double sn) {
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMaximumFractionDigits(0);

        String str = numberFormat.format(sn);
        String[] strArray = str.split(",");
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < strArray.length; i++) {
            buffer.append(strArray[i]);
        }
        return buffer.toString();
    }

    /**
     * 收款审核操作流程
     *
     * @param skshId
     * @return
     */
    @Transactional
    public void checkSkshXyz(Long skshId, List<Xyz> xyzList) {
        Sfk sfk = this.findSkshDetail(skshId);
        List<Xyz> xyzList1 = sfk.getXyzList();
        for (Xyz xyz1 : xyzList1) {
            xyz1.setDeleted(1);
            xyz1.setLastUpdated(new Date());
            xyzDao.save(xyz1);
        }
        for (Xyz xyz : xyzList) {
            xyz.setNbgs(sfk.getSbgs());
            xyz.setDqje(Double.parseDouble(sfk.getSfje().toString()));
            xyz.setXyzsflx(sfk.getSfklx() == 3 || sfk.getSfklx() == 4 ? 0 : 1);
            xyz.setSfk(sfk);
            xyz.setStatus(1);
//            xyz.setLxe(Double.parseDouble(xyz.getDqje().toString()) * ((getDateEdit(xyz.getDqrq(), xyz.getJkrq())) * (xyz.getYll() / 100 / 30)));
            xyz.setLastUpdated(new Date());
            xyz.setCreateUser(YgService.getCurrentYg());
            xyz.setCreateOrgan(YgService.getCurrentYg().getZggs());
            xyz.setCreateDepartment(YgService.getCurrentYg().getZgjg());
            this.xyzDao.save(xyz);
        }
        sfk.setLastUpdated(new Date());
        sfk.setZt("yrz");
        sfk.setShrq(new Date());
        sfk.setShr(YgService.getCurrentYg());
        this.skshDao.save(sfk);
    }

    /**
     * 付款审核操作流程
     *
     * @param skshId
     * @return
     */
    @Transactional
    public void checkSksh(Long skshId, Long nbkhhId) {
        Sfk sfk = this.findSkshDetail(skshId);
        sfk.setNbkhh(khhService.findKhhById(nbkhhId));
        sfk.setLastUpdated(new Date());
        sfk.setZt("yrz");
        sfk.setRzr(YgService.getCurrentYg());
        this.skshDao.save(sfk);
        // 保存收款金额等信息
        saveKyzj(skshId);
    }


    /**
     * 保存可用收款金额信息
     *
     * @param skid
     */
    private void saveKyzj(Long skid) {
        Sfk sk = this.skshDao.get(skid);
        Kyzj kyzjTemp;
        if (null != sk) {
            kyzjTemp = new Kyzj();
            kyzjTemp.setNbgs(sk.getSbgs());
            kyzjTemp.setGsjg(sk.getGldw());
            kyzjTemp.setKyzj(sk.getSfje());
            kyzjTemp.setSfsy("0");
            kyzjTemp.setCreateUser(YgService.getCurrentYg());
            kyzjTemp.setCreateOrgan(YgService.getCurrentYg().getZggs());
            kyzjTemp.setCreateDepartment(YgService.getCurrentYg().getZgjg());
            kyzjTemp.setLastUpdated(new Date());
            this.kyzjDao.save(kyzjTemp);
        }
    }

    /**
     * 关联判断
     *
     * @param sfk
     */
    private void nullId(Sfk sfk) {
        if (sfk != null && sfk.getPjlx() != null && sfk.getPjlx().getId() == null)
            sfk.setPjlx(null);
        if (sfk != null && sfk.getGldw() != null && sfk.getGldw().getId() == null)
            sfk.setGldw(null);
        if (sfk != null && sfk.getHklx() != null && sfk.getHklx().getId() == null)
            sfk.setHklx(null);
        if (sfk != null && sfk.getSbgs() != null && sfk.getSbgs().getId() == null)
            sfk.setSbgs(null);
        if (sfk != null && sfk.getSbbm() != null && sfk.getSbbm().getId() == null)
            sfk.setSbbm(null);
        if (sfk != null && sfk.getSbr() != null && sfk.getSbr().getId() == null)
            sfk.setSbr(null);
        if (sfk != null && sfk.getHt() != null && sfk.getHt().getId() == null)
            sfk.setHt(null);
    }

    /**
     * 查询可以资金
     *
     * @param date
     */
    public List findKyzjByDate(Date date) {
        // 查询所有可以使用的资金
        String querySql = "  select sum(kyzj) as sumKyzj, t.nbgs_id as nbgsId, t.gsjg_id as qyjgId " +
                " from t_biz_kyzj t" +
                " where t.date_created < ? and t.sfsy = 0 " +
                " group by t.nbgs_id, t.gsjg_id ";
        List kyzjList = this.kyzjDao.findBySQL(querySql, date);

        // 把资金改为已经使用
        String updateSql = " update T_BIZ_KYZJ t set t.sfsy=1,t.last_updated=? where t.date_created <? and t.sfsy = 0 ";
        this.kyzjDao.executeSQL(updateSql, date, date);

        return kyzjList;
    }

    /**
     * 更新或者保存可以资金总数表
     *
     * @param kyzjSum
     * @param qyjgId
     * @param nbgsId
     */
    @Transactional
    public void saveOrUpdate(Double kyzjSum, Long nbgsId, Long qyjgId) {
        String saveOrUpdateSql = "merge into t_biz_kyzjzs tk " +
                "using dual b " +
                "on (tk.nbgs_id = ? and tk.qyjg_id = ?)  " +
                "when matched then " +
                "update set tk.kyzjzs = tk.kyzjzs + ?, tk.last_updated = sysdate " +
                "when not matched then " +
                "insert(tk.id, tk.nbgs_id,tk.qyjg_id,tk.kyzjzs, tk.createuser_id,tk.date_created,tk.deleted) " +
                " values(seq_biz_kyzjzs.nextval, ?, ?, ?, 1, sysdate,0)";
        this.kyzjzsDao.executeSQL(saveOrUpdateSql, nbgsId, qyjgId, kyzjSum, nbgsId, qyjgId, kyzjSum);
    }

    /**
     * 查询可用资金总数
     *
     * @return
     */
    public List<Kyzjzs> findAllKyzjzs() {
        return this.kyzjzsDao.findAll();
    }

    /**
     * 更新可用资金总数
     *
     * @param kyzjzsId
     * @param sum
     */
    @Transactional
    public void updateKyzjzs(Long kyzjzsId, Double sum) {
        Kyzjzs kyzjzsTemp = this.kyzjzsDao.get(kyzjzsId);
        kyzjzsTemp.setKyzjzs(sum);
        kyzjzsTemp.setLastUpdated(new Date());
        this.kyzjzsDao.save(kyzjzsTemp);
    }

    public Long getDateEdit(Date date1, Date date2) {
        Long times = date1.getTime() - date2.getTime();
        return times / 24 / 60 / 60 / 1000;
    }


    public Cght findMxtsTxl() {
        Cght cght = this.cghtDao.findMxtsTxl();
        return cght;
    }

    @Autowired
    public void setBmService(BmService bmService) {
        this.bmService = bmService;
    }

    @Autowired
    public void setSkshDao(SkshDao skshDao) {
        this.skshDao = skshDao;
    }

    @Autowired
    public void setGsjgDao(GsjgDao gsjgDao) {
        this.gsjgDao = gsjgDao;
    }


    @Autowired
    public void setKhhService(KhhService khhService) {
        this.khhService = khhService;
    }

    @Autowired
    public void setPjglService(PjglService pjglService) {
        this.pjglService = pjglService;
    }

    @Autowired
    public void setKyzjDao(KyzjDao kyzjDao) {
        this.kyzjDao = kyzjDao;
    }

    @Autowired
    public void setKyzjzsDao(KyzjzsDao kyzjzsDao) {
        this.kyzjzsDao = kyzjzsDao;
    }

    @Autowired
    public void setXyzService(XyzService xyzService) {
        this.xyzService = xyzService;
    }

    @Autowired
    public void setXyzDao(XyzDao xyzDao) {
        this.xyzDao = xyzDao;
    }

    @Autowired
    public void setPjglDao(PjglDao pjglDao) {
        this.pjglDao = pjglDao;
    }

    @Autowired
    public void setEjzhDao(EjzhDao ejzhDao) {
        this.ejzhDao = ejzhDao;
    }

    @Autowired
    public void setDxpzService(DxpzService dxpzService) {
        this.dxpzService = dxpzService;
    }

    @Autowired
    public void setSjzdzDao(SjzdzDao sjzdzDao) {
        this.sjzdzDao = sjzdzDao;
    }

    @Autowired
    public void setCghtDao(CghtDao cghtDao) {
        this.cghtDao = cghtDao;
    }
}